<template>
  <div class="page art-full-height">
    <Search
      v-show="showSearchBar"
      v-model="searchForm"
      :resource-type-list="resourceTypeList"
      @search="handleSearch"
      @reset="resetSearchParams"
    ></Search>

    <ElCard
      class="art-table-card"
      shadow="never"
      :style="{ 'margin-top': showSearchBar ? '12px' : '0' }"
    >
      <ArtTableHeader
        v-model:columns="columnChecks"
        v-model:showSearchBar="showSearchBar"
        :loading="loading"
        @refresh="refreshData"
      >
        <template #left>
          <ElSpace wrap style="margin-right: 5px">
            <ElButton v-auth="'common:upload:upload'" @click="onUploadClick" v-ripple
              >上传资源</ElButton
            >
            <input ref="uploadRef" type="file" class="nond" @change="handleFileChange" />
          </ElSpace>
          <ElSpace wrap style="margin-right: 5px">
            <ElButton v-auth="'common:upload:delete'" @click="deleteRole()" v-ripple
              >删除资源</ElButton
            >
          </ElSpace>
        </template>
      </ArtTableHeader>

      <!-- 表格 -->
      <ArtTable
        :loading="loading"
        :data="data"
        :columns="columns"
        :pagination="pagination"
        @selection-change="handleSelectionChange"
        @pagination:size-change="handleSizeChange"
        @pagination:current-change="handleCurrentChange"
      >
      </ArtTable>
    </ElCard>
    <Dialog
      v-model="dialogVisible"
      :dialog-type="dialogType"
      :role-data="currentData"
      :resource-type-list="resourceTypeList"
      @success="refreshData"
    />
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted } from 'vue'
  import { useTable } from '@/composables/useTable'
  import {
    fetchResourceList,
    fetchResourceTypes,
    deleteFileApi,
    uploadResource
  } from '@/api/common'
  import ArtButtonTable from '@/components/core/forms/art-button-table/index.vue'
  import Search from './modules/search.vue'
  import Dialog from './modules/dialog.vue'
  import { ElTag, ElMessageBox, ElTooltip, ElImage } from 'element-plus'
  import { useAuth } from '@/composables/useAuth'
  import { getFullImageUrl } from '@/utils/image'
  const { hasAuth } = useAuth()

  // 选中行
  const selectedRows = ref<any[]>([])
  // 搜索表单
  const searchForm = ref({
    search: undefined,
    app: undefined,
    created_at: undefined
  })
  const resourceTypeList = ref<Array<{ id: number; name: string }>>([])
  const getCategoryName = (id: number | string) => {
    const found = resourceTypeList.value.find((r) => String(r.id) === String(id))
    return found ? found.name : ''
  }
  const dialogVisible = ref(false)
  const showSearchBar = ref(false)
  const dialogType = ref<any>('edit') // 或默认值
  const currentData = ref<any>({})
  const {
    columns,
    columnChecks,
    data,
    loading,
    pagination,
    getData,
    searchParams,
    resetSearchParams,
    handleSizeChange,
    handleCurrentChange,
    refreshData
  } = useTable({
    // 核心配置
    core: {
      apiFn: fetchResourceList,
      apiParams: {
        current: 1,
        size: 20
      },
      // 排除 apiParams 中的属性
      excludeParams: ['daterange'],
      columnsFactory: () => [
        { type: 'selection' }, // 勾选列
        {
          prop: 'id',
          label: 'ID',
          width: 100
        },
        {
          prop: 'avatar',
          label: '图片上传信息',
          width: 280,
          formatter: (row: { app: number; url: string; username: string }) => {
            const appMap: Record<
              number,
              { type: 'success' | 'warning' | 'primary'; text: string }
            > = {
              1: { type: 'success', text: '前台' },
              2: { type: 'warning', text: '后台' },
              3: { type: 'primary', text: 'API' }
            }
            const appConfig = appMap[row.app] || { type: 'info', text: String(row.app) }
            return h('div', { class: 'user', style: 'display: flex; align-items: center' }, [
              h(ElImage, {
                class: 'avatar',
                src: getFullImageUrl(row.url),
                previewSrcList: [getFullImageUrl(row.url)],
                previewTeleported: true,
                style:
                  'width: 40px; height: 40px; object-fit: cover; border-radius: 4px;margin-right: 5px;'
              }),
              h('div', {}, [
                h('p', { class: 'user-name' }, row.username),
                h(
                  ElTag,
                  {
                    type: appConfig.type as 'success' | 'info' | 'warning' | 'primary' | 'danger',
                    style: 'margin-top: 4px;'
                  },
                  () => appConfig.text
                )
              ])
            ])
          }
        },
        {
          prop: 'cate_id',
          label: '所属分类',
          minWidth: 140,
          formatter: (row: any) => {
            return getCategoryName(row.cate_id ?? row.type ?? row.app)
          }
        },
        {
          prop: 'storage',
          label: '位置',
          minWidth: 120
        },
        {
          prop: 'extension',
          label: '文件后缀',
          minWidth: 120,
          formatter: (row: any) => {
            return h(
              ElTooltip,
              { content: row.url || '无URL', placement: 'top' },
              {
                default: () => row.extension
              }
            )
          }
        },
        {
          prop: 'created_at',
          label: '操作日期',
          width: 180,
          sortable: true
        },
        {
          prop: 'operation',
          label: '操作',
          width: 140,
          fixed: 'right', // 固定列
          formatter: (row) => {
            return h('div', { style: 'text-align: right' }, [
              hasAuth('common:upload:move') &&
                h(
                  ElTooltip,
                  { content: '编辑', placement: 'top' },
                  {
                    default: () =>
                      h(ArtButtonTable, {
                        type: 'edit',
                        onClick: () => showDialog('edit', row)
                      })
                  }
                ),
              hasAuth('common:upload:delete') &&
                h(
                  ElTooltip,
                  { content: '删除', placement: 'top' },
                  {
                    default: () =>
                      h(ArtButtonTable, {
                        type: 'delete',
                        onClick: () => deleteRole(row)
                      })
                  }
                )
            ])
          }
        }
      ]
    }
  })
  onMounted(async () => {
    const res = (await fetchResourceTypes({})) as
      | { data?: { data?: Array<{ id: number; name: string }> } }
      | { data?: Array<{ id: number; name: string }> }
      | Array<{ id: number; name: string }>
    resourceTypeList.value = (res as any)?.data?.data ?? (res as any)?.data ?? res ?? []
  })
  /**
   * 搜索处理
   * @param params 搜索参数
   */
  const handleSearch = (params: Record<string, any>) => {
    // 处理日期区间参数，把 daterange 转换为 startTime 和 endTime
    const { daterange, ...filtersParams } = params
    const [startTime, endTime] = Array.isArray(daterange) ? daterange : [null, null]

    // 搜索参数赋值
    Object.assign(searchParams, { ...filtersParams, startTime, endTime })
    if (params.cate_id !== undefined) searchParams.cate_id = params.cate_id
    getData()
  }
  // 上传
  const uploadRef = ref()

  const onUploadClick = () => {
    if (uploadRef.value) {
      uploadRef.value.click()
    }
  }
  const handleFileChange = async (event: Event) => {
    const target = event.target as HTMLInputElement
    const file = target?.files?.[0]
    if (!file) return
    const formData = new FormData()
    formData.append('file', file)
    try {
      await uploadResource(formData)
      ElMessage.success('上传成功')
      refreshData()
    } catch {
      ElMessage.error('上传失败')
    }
  }
  const showDialog = async (type: 'edit', row?: any) => {
    dialogType.value = type
    currentData.value = row ? { ...row } : {}
    dialogVisible.value = true
  }

  const deleteRole = (row?: any) => {
    if (row) {
      ElMessageBox.confirm(`确定要删除【${row.id}】吗？`, '删除用户', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(async () => {
        await deleteFileApi([row.id])
        ElMessage.success('删除成功')
        getData()
      })
      return
    }
    // 批量删除
    if (!selectedRows.value.length) {
      ElMessage.warning('请先勾选要删除的用户')
      return
    }
    ElMessageBox.confirm(`确定要删除选中的${selectedRows.value.length}条数据吗？`, '批量删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    }).then(async () => {
      const ids = selectedRows.value.map((item) => item.id)
      await deleteFileApi(ids)
      ElMessage.success('批量删除成功')
      getData()
    })
  }
  /**
   * 处理表格行选择变化
   */
  const handleSelectionChange = (selection: any[]): void => {
    selectedRows.value = selection
    console.log('选中行数据:', selectedRows.value)
  }
</script>

<style lang="scss" scoped>
  .page {
    padding-bottom: 15px;
  }
  .nond {
    display: none;
  }
</style>
